package com.zjs.jsp.status.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zjs.jsp.domain.stats.*;
import com.zjs.jsp.status.mongodb.jsp_locationMagRepository;
import com.zjs.jsp.status.mongodb.jsp_orderstatusRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author 李文
 * @create 2018-07-26 10:56
 **/
@Service
public class ProcessingService
{
    public static Map<Integer, Integer> status = new HashMap<>();

    static {
        status.put(30, 20);
        status.put(40, 30);
        status.put(50, 40);
        status.put(60, 40);
        status.put(80, 40);
    }

    private static final Logger LOGGER = LoggerFactory.getLogger(ProcessingService.class);
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    java.text.DecimalFormat Decimalformat = new java.text.DecimalFormat("0.00000000000000");


    @Autowired
    private jsp_orderstatusRepository orderstatusRepository;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private jsp_locationMagRepository template;
    @Autowired
    IBaseEngineData baseEngineData;

    @Autowired
    SendCloudService sendCloudService;

    public void sendOrderStatus(String uuid, JspStatus mm, OrderStatus orderStatus) {

        // 判断是否发送过之前的状态
        // 是 发送
        // 否 不发送
        if (orderStatus != null) {
            if (isExistsStatusOver(orderStatus)) {
                if (sendCloudService.PushMessageHandle(uuid, orderStatus)) {
                    // 插入数据库
                    orderStatus.setSu(1);
                    orderStatus.setDate(new Date());
                    orderstatusRepository.insert(orderStatus);
                } else {
                    orderStatus.setSu(0);
                    orderstatusRepository.insert(orderStatus);
                }
            } else {
                orderStatus.setSu(0);
                orderstatusRepository.insert(orderStatus);
            }
        } else {
            LOGGER.warn("状态数据为空 {}", mm.toString());
        }

    }

    public List<OrderStatus> getOrderStatusList(String uuid, JspStatus mm, Long time) throws Exception {

        // 推送的是有订单编码没有任务编码
        if (mm.getTaskCode() == null && mm.getOrderCode() != null) {
            // 有多条订单的时候
            if ("00".equals(mm.getStatus())) {
                return null;
            }
            return multipleOrders(uuid, mm);
        } else {
            // 推送的是有任务编码没有订单编码
            if (mm.getTaskCode() == null) {
                return null;
            }
            return getTaskOrder(uuid, mm, time);
        }
    }


    public boolean isExistsStatusOver(OrderStatus orderStatus) {
        //临时添加 65 通过
        if ("62".equals(orderStatus.getOs()) || "65".equals(orderStatus.getOs())) {
            return true;
        }
        return orderstatusRepository.existsByPocAndSuAndOs(
                orderStatus.getPoc(),
                orderStatus.getSu(),
                status.get(orderStatus.getOs()));

    }


    private List<OrderStatus> getTaskOrder(String uuid, JspStatus mm, Long time) throws Exception {
        List<OrderStatus> orderStatusList = new ArrayList<>();
        // 多条任务状态处理
        // 任务编码有时候是多个
        // {"taskCode":"4a0a61d3e70247d8a6d2952a00cefc37,ffe30eb6d017466fb7ab1d656679bef3,994cdc7ef8e44b1a9e39eba93fd112ac,93e0074db8b5439ea627e5913ca29899","orderCode":null,"status":"20","excpCode":null,"excpNote":null}
        for (String taskCode : mm.getTaskCode().split(",")) {
            LOGGER.info("{} taskCode:{}", uuid, taskCode);
            RootData rd = getTaskRootData(time, taskCode);
            List<OrderData> jt = null;
            if (rd != null && "Y".equals(rd.getStatus())) {
                jt = rd.getData();
            }
            if (jt != null && jt.size() > 0) {

                for (OrderData item : jt) {

                    StatusRoot sr1 = getOrderStatus(uuid, item.getOrderCode(), mm.getStatus());
                    if (sr1 != null && sr1.getData() != null && sr1.getData().getIsCancle() != null
                            && sr1.getData().getIsCancle().equals(0)) {

                        LOGGER.info("{} 任务获取接口数据:{}", uuid, objectMapper.writeValueAsString(sr1));
                        OrderStatus os = sr1.getData().toOrderStatus();
                        // 获取派送员
                        Msgnt m = getRiderInformation(sr1);
                        os.setLng(m.getLng());
                        os.setLat(m.getLat());
                        orderStatusList.add(os);
                    }
                }
            }
        }
        return orderStatusList;
    }

    public List<OrderStatus> multipleOrders(String uuid, JspStatus mm) throws Exception {
        // {"taskCode":null,"orderCode":"65886696,65886735","status":"30","excpCode":null,"excpNote":null}

        List<OrderStatus> orderStatusList = new ArrayList<>();
        for (String orderCode : mm.getOrderCode().split(",")) {

            // 直接用订单编号+状态查状态信息
            StatusRoot sr = getOrderStatus(uuid, orderCode, mm.getStatus());
            if (sr != null && sr.getData() != null) {
                LOGGER.info(" {} 获取接口数据:{}", uuid, objectMapper.writeValueAsString(sr));
                OrderStatus os = sr.getData().toOrderStatus();
                // 获取骑手信息
                Msgnt m = getRiderInformation(sr);
                os.setLat(m.getLat());
                os.setLng(m.getLng());
                orderStatusList.add(os);
            } else {
                throw new Exception("没有查询到状态数据,稍后重试处理 mm:" + mm.toString());
            }
        }
        return orderStatusList;
    }

    public Msgnt getRiderInformation(StatusRoot sr) {
        Msgnt m = new Msgnt();
        if (StringUtils.isEmpty(sr.getData().getLocationJD())) {
            jsp_locationMsg jlm = template.findByUserIDOrderByTimeDesc(sr.getData().getUserCode());

            if (jlm != null) {
                if (jlm.getLat().contains("E") || jlm.getLon().contains("E")
                        || jlm.getLat().contains("e") || jlm.getLon().contains("e")) {
                    m.setLat(new BigDecimal(Decimalformat.format(40.12052700000000)));
                    m.setLng(new BigDecimal(Decimalformat.format(116.59327700000000)));
                } else {
                    m.setLat(new BigDecimal(Decimalformat
                            .format(jlm.getLat() == null ? 0 : Double.parseDouble(jlm.getLat()))));
                    m.setLng(new BigDecimal(Decimalformat
                            .format(jlm.getLon() == null ? 0 : Double.parseDouble(jlm.getLon()))));
                }
            } else {
                m.setLat(new BigDecimal(Decimalformat.format(40.12052700000000)));
                m.setLng(new BigDecimal(Decimalformat.format(116.59327700000000)));
            }
        } else {
            m.setLat(new BigDecimal(Decimalformat.format(Double.parseDouble(sr.getData().getLocationWD()))));
            m.setLng(new BigDecimal(Decimalformat.format(Double.parseDouble(sr.getData().getLocationJD()))));
        }

        return m;
    }


    public StatusRoot getOrderStatus(String uuid, String orderCode, String orderStatus) throws Exception {
        LOGGER.info("{} 查询状态信息orderCode:{},orderStatus:{}", uuid, orderCode, orderStatus);
        StatusRoot sr;
        try {
            sr = baseEngineData.getOrderStatus(orderCode, orderStatus);
        } catch (Exception e) {
            throw new Exception("调用SS-ERP-ENGINE-REST/engine/getOrderStatus 服务异常", e);
        }
        if ("Y".equals(sr.getStatus())) {
            return sr;
        } else {
            LOGGER.info("{} 调用当天数据不等于Y {}  查询历史数据 ", uuid, sr);
            return getHisOrderStatus(uuid, orderCode, orderStatus);
        }
    }

    private StatusRoot getHisOrderStatus(String uuid, String orderCode, String orderStatus) throws Exception {
        LOGGER.info("{}查询历史状态信息orderCode:{},orderStatus:{}", uuid, orderCode, orderStatus);
        StatusRoot sr;
        try {
            sr = baseEngineData.getHisOrderStatus(orderCode, orderStatus);
        } catch (Exception e) {
            throw new Exception("调用SS-ERP-ENGINE-REST/engine/getOrderStatus 服务异常", e);
        }

        if ("Y".equals(sr.getStatus())) {
            return sr;
        } else {
            throw new Exception(" 返回结果异常 " + sr.getInfo());
        }
    }

    /**
     * 判断从mq接收过来的数据 是否是当天产生的 如果当天产生的 返回true 否则 false
     *
     * @param time
     */
    private boolean todayData(final long time) {
        long timestampt = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

        int nowtoday = (int) (timestampt / 86400000);
        int otherday = (int) (time / 86400000);

        if (nowtoday == otherday) {
            return true;
        } else {
            return false;
        }
    }


    private RootData getTaskRootData(Long time, String taskCode) throws Exception {
        try {
            if (todayData(time)) {
                return baseEngineData.getOrdersByTaskCode(taskCode);
            } else {
                return baseEngineData.getHisOrdersByTaskCode(taskCode);
            }
        } catch (Exception e) {
            throw new Exception("调用SS-ERP-ENGINE-REST/engine/getHisOrdersByTaskCode|getOrdersByTaskCode  服务异常", e);
        }
    }
}
